package com.example.exam1.dao;

import com.example.exam1.entity.User;
import com.example.exam1.util.JDBCUtils;

import java.sql.*;

/**
 * @author wushuang
 * recorrected by Deepwind
 */

public class UserDao {
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;


    /**
     * 添加用户
     * @param user User
     * @return 状态码
     */
    public int addUser(User user) {
        int count = 0;
        try {
            conn = JDBCUtils.getConn();

            String sql = "insert into tb_user (username,password) value (?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            count = ps.executeUpdate();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, ps, conn);
        }
        return count;
    }

    /**
     * 查询用户
     * @param user User
     * @return User
     */
    public User searchUser(User user) {
        // 你可以把下面的变量叫做user1，但是不推荐，变量名应包含语义
        User tmpUser = null;
        try {
            conn = JDBCUtils.getConn();

            String sql = "select * from tb_user where username = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            rs = ps.executeQuery();
            while (rs.next()) {
                tmpUser = new User();
                tmpUser.setId(rs.getInt("id"));
                tmpUser.setUsername(rs.getString("username"));
                tmpUser.setPassword(rs.getString("password"));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, ps, conn);
        }
        return tmpUser;
    }

    public boolean isUserExisted(User user) {
        return searchUser(user) != null;
    }


}
